#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
#include<vector>
using namespace std;
// Definition for a Node.
class Node {
public:
    int val;
    Node* left;
    Node* right;

    Node() {}

    Node(int _val) {
        val = _val;
        left = NULL;
        right = NULL;
    }

    Node(int _val, Node* _left, Node* _right) {
        val = _val;
        left = _left;
        right = _right;
    }
};

class Solution {
public:
    void zhongxu(Node* root, Node*& prev)
    {
        Node* cur = root;
        if (cur == nullptr)
        {
            return;
        }
        zhongxu(cur->left, prev);
        cur->left = prev;
        if (prev != nullptr)
        {
            prev->right = cur;
        }
        prev = cur;
        zhongxu(cur->right, prev);
    }
    Node* treeToDoublyList(Node* root) {
        if (root == nullptr)
            return nullptr;
        Node* prev = nullptr;
        zhongxu(root, prev);
        Node* head = root;
        while (head && head->left)
        {
            head = head->left;
        }
        head->left = prev;
        prev->right = head;
        return head;
    }
};
int main()
{
    Solution as;
    Node* aq;
    as.treeToDoublyList(aq);
	return 0;
}